package com.wuneng.ircontrol.myUtil.common;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.storage.StorageManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;

import com.wuneng.commonlibrary.util.StorageInfo;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;


public class Util {

    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    public static String printData(byte[] data) {
        StringBuffer buffer = new StringBuffer();
        for (byte s : data) {
            int a = s & 0xFF;
            buffer.append(a);
            buffer.append(",");
        }
        return buffer.toString();
    }


    /**
     * 获取手机的MAC地址
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static String getMac1() throws Exception {
        String address = null;
        // 把当前机器上的访问网络接口的存入 Enumeration集合中
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface netWork = interfaces.nextElement();
            // 如果存在硬件地址并可以使用给定的当前权限访问，则返回该硬件地址（通常是 MAC）。
            byte[] by = netWork.getHardwareAddress();
            if (by == null || by.length == 0) {
                continue;
            }
            StringBuilder builder = new StringBuilder();
            for (byte b : by) {
                builder.append(String.format("%02X:", b));
            }
            if (builder.length() > 0) {
                builder.deleteCharAt(builder.length() - 1);
            }
            String mac = builder.toString();
            Log.d("mac", "interfaceName=" + netWork.getName() + ", mac=" + mac);
            // 从路由器上在线设备的MAC地址列表，可以印证设备Wifi的 name 是 wlan0
            if (netWork.getName().equals("wlan0")) {
                Log.d("mac", " interfaceName =" + netWork.getName() + ", mac=" + mac);
                address = mac;
            }
        }
        address = address.replace(":", "").toUpperCase();
        address = address.replace(".", "");
        return address;
    }

    /**
     * 获取32位UUID编号
     *
     * @return
     */
    public static String GetUUID() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        Log.d("debug", "----->UUID" + uuid);
        return uuid;
    }

    /**
     * 获取当前系统时间
     *
     * @return
     */
    public static String GetNowTime() {
        String reslut = "";
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        reslut = sDateFormat.format(new java.util.Date());
        return reslut;
    }

    /**
     * 获取当前系统时间
     *
     * @return
     */
    public static String GetNowTimeWithoutSecond() {
        String reslut = "";
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        reslut = sDateFormat.format(new java.util.Date());
        return reslut;
    }

    /**
     * 打开或关闭wifi
     *
     * @param context
     * @param open
     * @return
     */
    public static boolean openWifi(Context context, boolean open) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        return wm.setWifiEnabled(open);
    }

    /**
     * 获取当前系统日期
     *
     * @return
     */
    public static String GetNowDay() {
        String reslut = "";
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        reslut = sDateFormat.format(new java.util.Date());
        return reslut;
    }

    /**
     * 获取本月第一天
     *
     * @return
     */
    public static String getMonthStart() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取当前系统时间前N天的时间 N为- 前n天 N为+ 后n天
     *
     * @return
     */
    public static String getNextDay(int n, String time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String reslut = "";
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(sDateFormat.parse(time));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        calendar.add(Calendar.DAY_OF_MONTH, n);

        reslut = sDateFormat.format(calendar.getTime());
        return reslut;
    }

    /**
     * 时间String to DateTime
     */
    public static Date ChangeStrToDateTime(String str) {
        Date date = new java.util.Date();
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            date = sDateFormat.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return date;
    }

    /**
     * 时间String to DateTime
     */
    public static Date ChangeStrToDateTimeTime(String str) {
        Date date = new java.util.Date();
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            date = sDateFormat.parse(str);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return date;
    }

    /**
     * 获取当前系统日期
     *
     * @return
     */
    public static String ChangeDateTimeToStr(Date time) {
        String reslut = "";
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        reslut = sDateFormat.format(time);
        return reslut;
    }

    /**
     * <pre>
     * 判断date和当前日期是否在同一周内
     * 注:
     * Calendar类提供了一个获取日期在所属年份中是第几周的方法，对于上一年末的某一天
     * 和新年初的某一天在同一周内也一样可以处理，例如2012-12-31和2013-01-01虽然在
     * 不同的年份中，但是使用此方法依然判断二者属于同一周内
     * </pre>
     *
     * @param date
     * @return
     */
    public static boolean isSameWeekWithToday(String date) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = format.parse(date);
            d2 = format.parse(Util.GetNowDay());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();
        cal1.setTime(d1);
        cal2.setTime(d2);
        int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        //subYear==0,说明是同一年
        if (subYear == 0) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        //例子:cal1是"2005-1-1"，cal2是"2004-12-25"
        //java对"2004-12-25"处理成第52周
        // "2004-12-26"它处理成了第1周，和"2005-1-1"相同了
        //大家可以查一下自己的日历
        //处理的比较好
        //说明:java的一月用"0"标识，那么12月用"11"
        else if (subYear == 1 && cal2.get(Calendar.MONTH) == 11) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;
        }
        //例子:cal1是"2004-12-31"，cal2是"2005-1-1"
        else if (subYear == -1 && cal1.get(Calendar.MONTH) == 11) {
            if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
                return true;

        }
        return false;

    }

    /**
     * 获取系统版本信息
     *
     * @return
     */
    public static int getVersionCode(Context cx) throws Exception {
        String versionName = null;
        PackageManager packageManager = cx.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(cx.getPackageName(), 0);
        versionName = packInfo.versionName;
        String packageName = packInfo.packageName;
        int versionCode = packInfo.versionCode;
        ApplicationInfo appInfo = packInfo.applicationInfo;
        Drawable icon = packageManager.getApplicationIcon(appInfo);

        return versionCode;
    }

    /**
     * 获取系统版本Name
     *
     * @return
     */
    public static String getVersionName(Context cx) throws Exception {
        String versionName = null;
        PackageManager packageManager = cx.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(cx.getPackageName(), 0);
        versionName = packInfo.versionName;

        return versionName;
    }

    /**
     * 获取系统包名
     *
     * @return
     */
    public static String getPackageName(Context cx) throws Exception {
        PackageManager packageManager = cx.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(cx.getPackageName(), 0);
        String packageName = packInfo.packageName;

        return packageName;
    }


    public static List<String> getColumnData(Context ctx, Uri uri, String column, String selection, String[] selectionArgs, String SortOrder) {
        List<String> columnsStringList = new ArrayList<String>();

        Cursor cursor = ctx.getContentResolver().query(uri, null, selection, selectionArgs, SortOrder);

        int columnID = cursor.getColumnIndex(column);// 取得字段的ID值
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

            columnsStringList.add(cursor.getString(columnID));

        }
        if (cursor != null) {
            cursor.close();
        }
        return columnsStringList;
    }


    /**
     * 获取内部存储卡地址 返回：内部存储卡路径，是可移除的SD卡还是不移除的sd卡，如果没有，则返回空
     *
     * @param context
     * @return
     */
    public static String GetStoragePath(Context context, boolean isRemoveable) {
        List<StorageInfo> list = listAvaliableStorage(context);

        boolean Removeable = isRemoveable;

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isRemoveable == Removeable)// 无法卸载的为内部存储器
            {
                return list.get(i).path;
            }

        }
        return "";
    }

    /**
     * 获取到Android设备所有存储器
     *
     * @param context
     * @return
     */
    public static List<StorageInfo> listAvaliableStorage(Context context) {
        ArrayList<StorageInfo> storagges = new ArrayList<StorageInfo>();
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        try {
            Class<?>[] paramClasses = {};
            Method getVolumeList = StorageManager.class.getMethod("getVolumeList", paramClasses);
            getVolumeList.setAccessible(true);
            Object[] params = {};
            Object[] invokes = (Object[]) getVolumeList.invoke(storageManager, params);
            if (invokes != null) {
                StorageInfo info = null;
                for (int i = 0; i < invokes.length; i++) {
                    Object obj = invokes[i];
                    Method getPath = obj.getClass().getMethod("getPath", new Class[0]);
                    String path = (String) getPath.invoke(obj, new Object[0]);
                    info = new StorageInfo(path);
                    File file = new File(info.path);
                    if ((file.exists()) && (file.isDirectory()) && (file.canWrite())) {
                        Method isRemovable = obj.getClass().getMethod("isRemovable", new Class[0]);
                        String state = null;
                        try {
                            Method getVolumeState = StorageManager.class.getMethod("getVolumeState", String.class);
                            state = (String) getVolumeState.invoke(storageManager, info.path);
                            info.state = state;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (info.isMounted()) {
                            info.isRemoveable = ((Boolean) isRemovable.invoke(obj, new Object[0])).booleanValue();
                            storagges.add(info);
                        }
                    }
                }
            }
        } catch (NoSuchMethodException e1) {
            e1.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        storagges.trimToSize();

        return storagges;
    }

    /**
     * 修改权限
     *
     * @param f
     * @throws IOException
     * @throws InterruptedException
     */
    public static void changeMode(File f) throws IOException, InterruptedException {
        Process p = Runtime.getRuntime().exec("chmod 777 " + f.getAbsolutePath());
        int status = p.waitFor();
        if (status == 0) {
            System.out.println("sucess");
        } else {
            System.out.println("fail");
        }
    }


    // 隐藏输入框
    public static void HideImm(Context context) {
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } catch (Exception e) {

        }
    }

    //ping方法，ip为传入的ip地址
    public static int ping(String ip) {
        try {
            Runtime run = Runtime.getRuntime();
            Process proc = null;

            String str = "ping -c 1 -w 1 " + ip;
            System.out.println(str);
            proc = Runtime.getRuntime().exec(str);
            int result = proc.waitFor();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * list转string  以逗号拼接
     *
     * @param mList
     * @return
     */
    public static String listToString(List<String> mList) {
        String convertedListStr = "";
        if (null != mList && mList.size() > 0) {
            String[] mListArray = mList.toArray(new String[mList.size()]);
            for (int i = 0; i < mListArray.length; i++) {
                if (i < mListArray.length - 1) {
                    convertedListStr += mListArray[i] + ",";
                } else {
                    convertedListStr += mListArray[i];
                }
            }
            return convertedListStr;
        } else return "";
    }


    public static String getDeviceId(Context context) {
        String deviceId = "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (null != tm) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {

            } else {
                if (tm.getDeviceId() != null) {
                    deviceId = tm.getDeviceId();
                } else {
                    deviceId = Settings.Secure.getString(context.getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
                }
            }
            Log.d("deviceId--->", deviceId);
        }
        return "";
    }


}
